package com.he1618.boot3.app;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

public class ThreadApp {

    public static void main(String[] args) throws ExecutionException, InterruptedException {

        CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
            // 异步处理逻辑
            System.out.println("Async task is running");
        });

        // 主线程可以继续执行其他任务

        future.join(); // 阻塞等待异步任务完成

        Long time=System.currentTimeMillis();


        CompletableFuture<Integer> a1 = CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(1200);
                System.out.println("a1");
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            return 1;
        });

        CompletableFuture<Integer> a2 = CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(1200);
                System.out.println("a2");
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            return 2;
        });


        CompletableFuture<Integer> a3 = CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(1200);
                System.out.println("a3");
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            return 3;
        });


        CompletableFuture<Integer> a4 = CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(100);
                System.out.println("a4");
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            return 4;
        });
        System.out.println(a1.get());
        System.out.println(a2.get());
        System.out.println(a3.get());
        System.out.println(a4.get());
        System.out.println(a1.get());

        //CompletableFuture.allOf(a1, a2, a3, a4).join();
        time=System.currentTimeMillis()-time;
        System.out.println(time/1000.0);
    }
}
